package com.ssl.rms.utils;

import com.ssl.rms.constants.SystemConstant;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * http请求相关工具
 */
public class HttpUtil {
    /**
     * @param request
     * @return
     * @author xiongxiaotun <br/>
     * @Title isAjaxRequest  <br/>
     * @Description 判断是否是异步请求 <br/>
     * @version V1.0  <br/>
     */
    public static boolean isAjax(ServletRequest request) {
        if (!(request instanceof ServletRequest)) {
            return false;
        }
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestedWith = httpServletRequest.getHeader("x-requested-with");
        String contentType = httpServletRequest.getHeader("Content-Type");
        String mobileFlag = httpServletRequest.getHeader(SystemConstant.MOBILE_FLAG);

        return "XMLHttpRequest".equalsIgnoreCase(requestedWith) || "application/json".equals(contentType)
                || "ios".equals(mobileFlag) || "android".equals(mobileFlag) || "tablet".equals(mobileFlag);
    }

    /**
     * 输出字符到前端
     *
     * @param response
     * @param result
     * @throws IOException
     */
    public static void printResponse(ServletResponse response, Object result) throws IOException {
        if (!(response instanceof HttpServletResponse)) {
            return;
        }
        if (null == result) {
            return;
        }
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.reset();
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.println(JsonMapper.toJsonString(result));
        out.flush();
        out.close();
    }
}
